package com.jili.jwt.util;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.UUID;

/**
 * @author: Jili
 * @date: Created on 2021/6/24 16:35
 */
public class JwtUtil {
    //一天
    private static long time = 1000*60*60*24;

    //5s
    private static long time5s = 1000*5;

    private static String signature = "admin";

    public static String createToken() {
        JwtBuilder jwtBuilder= Jwts.builder();
        String jwtToken = jwtBuilder
                //Header
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                //payload
                .claim("username","admin")
                .claim("role","admin")
                //payload sub主题
                .setSubject("admin-test")
                //payload 有效时间
                .setExpiration(new Date(System.currentTimeMillis()+time5s))
                .setId(UUID.randomUUID().toString())
                //signature
                .signWith(SignatureAlgorithm.HS256,signature)
                //拼接
                .compact();
        return jwtToken;
    }

    public static boolean checkToken(String token){
        if(token == null){
            return false;
        }
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(signature).parseClaimsJws(token);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
